package com.zjh.reactive;

import reactor.core.publisher.Flux;
import reactor.core.publisher.SynchronousSink;

import java.time.Duration;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;

/**
 * @Auther: zjh
 * @Date: 2025/11/3 - 11 - 03 - 22:31
 * @Description: com.zjh.reactive
 * @version: 1.0
 */
public class Generator {
    public static void main1(String[] args) throws InterruptedException {
        Flux.generate(
                        // 通过Callable提供初始状态实例
                        new Callable<ArrayList<Long>>() {
                            @Override
                            public ArrayList<Long> call() throws Exception {
                                final ArrayList<Long> longs = new ArrayList<>();
                                longs.add(0L);
                                longs.add(1L);
                                return longs;
                            }
                        }, // 负责斐波拉契数列
                        // 函数第一个参数数据、函数第二个参数类型 、返回值
                        new BiFunction<ArrayList<Long>, SynchronousSink<Long>, ArrayList<Long>>() {
                            @Override
                            public ArrayList<Long> apply(ArrayList<Long> longs, SynchronousSink<Long> sink) {
                                Long aLong = longs.get(longs.size() - 1);
                                Long aLong1 = longs.get(longs.size() - 2);
                                sink.next(aLong);
                                longs.add(aLong + aLong1);
                                return longs;
                            }
                        })
                .log()
                .take(10)
                .subscribe(System.out::println);
        Thread.sleep(5000);
    }

    public static void main5(String[] args) {
        Flux<String> generate = Flux.generate(synchronousSink -> {


                synchronousSink.next("haha"); //一次只能向下游发送一个数据不能用循环
                synchronousSink.complete();//向Flux中放入数据
        });
        generate.subscribe(System.out::println);
        Flux.generate(
                ()->0,
                (startNum,sink)->{
                    if(startNum==4){
                        sink.complete();
                    }
                    sink.next(startNum);

                    return startNum+1;
                }
                ).subscribe(System.out::println);


    }

    public static void main(String[] args) {
        Flux.just("zhang san","li si")
                .flatMap(v->{
                   return Flux.fromArray(v.split(" "));
                }).subscribe(System.out::println);
    }
}
